﻿using Common.EnumEntity;
using Microsoft.Extensions.Configuration;
using Models.Entity;
using SqlSugar;

namespace ApiServer.Utilitys.InitDatabaseExt
{
    /// <summary>
    /// 初始化SqlSugar
    /// </summary>
    public static class InitSqlSugarExt
    {
        /// <summary>
        /// 初始化SqlSugar
        /// </summary>
        /// <param name="builder"></param>
        public static void InitSqlSugar(this WebApplicationBuilder builder)
        {
            CustomConnectionConfig customConnectionConfig = new CustomConnectionConfig();
            builder.Configuration.Bind("ConnectionStrings", customConnectionConfig);

            builder.Services.AddTransient<ISqlSugarClient>(s =>
            {
                ConnectionConfig connection = new ConnectionConfig()
                {
                    ConnectionString = customConnectionConfig.ConnectionString,
                    DbType = DbType.SqlServer,
                    IsAutoCloseConnection = true,
                    InitKeyType = InitKeyType.Attribute,
                  
                    //SlaveConnectionConfigs = customConnectionConfig
                    //    .SlaveConnectionConfigs.Select(c => new SlaveConnectionConfig()
                    //    {
                    //        ConnectionString = c.ConnectionString,
                    //        HitRate = c.CustomHitRate
                    //    })
                    //    .ToList()
                   
                };
                SqlSugarClient client = new SqlSugarClient(connection);

                client.Aop.DataExecuting = (s, p) =>
                {
                    if (
                        p.OperationType.Equals(DataFilterType.InsertByObject)
                        && "CreateTime".Equals(p.EntityColumnInfo.DbColumnName)
                    )
                    {
                        p.SetValue(DateTime.Now);
                    }

                    if (
                        p.OperationType.Equals(DataFilterType.UpdateByObject)
                        && "ModifyTime".Equals(p.EntityColumnInfo.DbColumnName)
                    )
                    {
                        p.SetValue(DateTime.Now);
                    }
                };

                client.Aop.OnLogExecuted = (s, p) =>
                {
                   
                    Console.WriteLine(
                        $"OnLogExecuted:输出Sql语句:{s} || 参数为：{string.Join(",", p.Select(p => p.Value))}"
                    );
                };
                client.Aop.OnError = e =>
                {
                    // if (e.Message.Contains("read-only"))
                    // {
                    //     // 自动切换到主库
                    //     client.ChangeDatabase();
                    // }
                    Console.WriteLine(
                        "*******************************************************************************************"
                    );
                    Console.WriteLine($"OnError:Sql语句执行异常:{e.Message}");
                };

                ////全局处理之后，后续只要是查询这些数据，自动多一个过滤条件
                //client.QueryFilter.AddTableFilter<Sys_Menu>(it => it.Status != (int)StatusEnum.Deleted);
                //client.QueryFilter.AddTableFilter<Sys_Role>(it => it.Status != (int)StatusEnum.Deleted);
                //client.QueryFilter.AddTableFilter<Sys_RoleMenuMap>(it => it.Status != (int)StatusEnum.Deleted);
                //client.QueryFilter.AddTableFilter<Sys_User>(it => it.Status != (int)StatusEnum.Deleted);
                //client.QueryFilter.AddTableFilter<Sys_UserRoleMap>(it => it.Status != (int)StatusEnum.Deleted);
                return client;
            });
        }
    }
}
